package com.mdd.mddapiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.mdd.mddapiclientsdk.model.User;
import com.mdd.mddapiclientsdk.utils.SignUtils;
import org.springframework.lang.Nullable;

import java.util.HashMap;
import java.util.Map;


/**
 * 调用第三方接口的客户端
 *
 * @author Mdd
 * @Github <a href="https://github.com/mdd123cc"/>
 * @Gitee <a href="https://gitee.com/mdd115192"/>
 */
public class MddApiClient {
    /**
     * 协议
     */
    private static final String AGREEMENT = "http://";
    /**
     * 网关主机
     */
    private static final String GATEWAY_HOST = "localhost:8090";


    private String accessKey;
    private String secretKey;


    public MddApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }


    /**
     * 统一发送请求给网关
     * @return
     */
    public String invokeInterface(@Nullable String userParams, String path, String method){
        String url = GATEWAY_HOST+path;
        Map<String, String> headers = getHeaderMap(userParams);
        String res = HttpRequest.post(url)
                .addHeaders(headers)
                .body(userParams)
                .execute().body();
        return JSONUtil.toJsonStr(res);

    }

    /**
     * 得到请求的headerMap
     * @param body
     * @return
     */
    Map<String,String> getHeaderMap(String body ){
        HashMap<String, String> headers = new HashMap<>();
        headers.put("accessKey",accessKey);
        headers.put("nonce", RandomUtil.randomNumbers(4));
        headers.put("timestamp",System.currentTimeMillis()+"");
        headers.put("body",body);
        headers.put("sign", SignUtils.getSign(body,secretKey));
        return headers;
    }

}
